<template>
	<view class="activityPage">
		<!-- 顶部导航 -->
		<mnav-bar fontColor="#FFF" title="活动墙" bgColor="none">
			<view slot="left">
				<image class="hicon" src="../static/back.png" mode="aspectFit" @tap="gotoHome()"/>
			</view>
		</mnav-bar>
		<view class="activityTabItem">
			<view class="tabItem orange " @click="changeTab('晒图征文')" :class="{active:activity_catagory=='晒图征文'}">
				<text>晒图征文</text>
				<text class="activeItem "></text>
			</view>
			<view class="tabItem green" @click="changeTab('投票')" :class="{active:activity_catagory=='投票'}">
				<text>投票</text>
				<text class="activeItem"></text>
			</view>
			<view class="tabItem blue" @click="changeTab('线下会')" :class="{active:activity_catagory=='线下会'}">
				<text>线下会</text>
				<text class="activeItem"></text>
			</view>
		</view>
		<scroll-view class="scrollView" @scrolltolower="activityScrollToLower" :refresher-enabled="true" :refresher-threshold="0"
					 refresher-default-style="white" @refresherrestore="onRestore" :refresher-triggered="activityTriggered"
					 @refresherrefresh="activityScrollRefresh" scroll-y :show-scrollbar="false">
			<view class="section" v-if="listData.data && listData.data.length>0">
				<!-- 遍历显示活动分栏 -->
				<view class="listItem" :key="index" v-for="(item, index) in listData.data">
					<!-- 如果是纯表单类型，直接跳转到对应的服务 -->
					<view class="list" v-if="item.activity_type === 'form_sub'" :data-type_status="item.type_status" :data-id="item.id" @click="goJoin">
						<view class="imgContainer">
							<image class="img" v-if=" item.images.length > 0 " :src="https + item.images[0].host + item.images[0].preview" mode="aspectFill" />
							<image class="img" v-else src="http://www.royole.com/image/catalog/banner/2020/home_banner_wing3_cn_2020032601.jpg" mode="aspectFill" />
						</view>
						<view class="content">
							<view class="content-left">
								<view class="title text-cut-2">{{item.name}}</view>
								<view class="activeContent" v-if="item && item.activity_type === 'form_sub'">{{item.detail}}</view>
								<view class="activeDetail" v-else>
									<view>{{ item.target_user_tag?item.target_user_tag:'全员参与' }} </view>
									<text v-if="item.start_time">·</text>
									<view v-if="item.start_time">{{item.start_time}}</view>
									<text v-if="item.address">·</text>
									<view v-if="item.address">{{item.area?item.area:''}}{{item.address}}</view>
								</view>
								<!-- <view class="signUpAtv"> -->
									<!-- 参加人员情况展示 -->
									<!-- <view class="atvList" v-if="item.persion_num > 0">
										<view class="atv" v-for="(itemDetail, index) in item.persion_image" :key="index" v-if="index < 3">
											<image v-if="itemDetail" mode="aspectFill" :src="itemDetail" />
											<image v-else mode="aspectFill" src="../static/sns/ry_avatar.png" />
										</view>
										<view class="joinNum">等{{ item.persion_num }}人参加</view>
									</view> -->
									<!-- 对应的还剩下多少名额显示 -->
									<!-- <view v-else-if="item.limit_persion_num > 0">
										<view class="joinNum onlyNum">{{item.limit_persion_num}}个名额，等你来参加</view>
									</view>
								</view> -->
							</view>
							<view class="signUpInfo">
								<view class="btnBox" :class="item.type_status === '未开始' || item.type_status === '已结束' ? 'gray' : ''">
									<view class="join">{{item.type_status}}</view>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 如果是活动类型，可以查看活动详情 -->
					<view class="list" v-else @click="todetail" :data-id="item.id" :data-type_status="item.type_status">
						<!-- 活动图片 -->
						<view class="imgContainer">
							<image class="img" v-if="item.images.length > 0" :src="https + item.images[0].host + item.images[0].preview" mode="aspectFill" />
							<image class="img" v-else src="http://www.royole.com/image/catalog/banner/2020/home_banner_wing3_cn_2020032601.jpg" mode="aspectFill" />
						</view>
						<view class="content">
							<view class="content-left">
								<view class="title text-cut-2">{{item.name}}</view>
								<!-- <view class="activeContent" v-if="item && item.activity_type === 'form_sub'">{{item.detail}}</view>
								<view class="activeDetail" v-else>
									<view>{{ item.target_user_tag ? item.target_user_tag : '全员参与' }} </view>
									<text v-if="item.start_time">·</text>
									<view v-if="item.start_time">{{item.start_time}}</view>
									<text v-if="item.address">·</text>
									<view v-if="item.address">{{item.area ? item.area : ''}}{{item.address}}</view>
								</view> -->
								<!-- 参加人员情况展示 -->
								<view class="signUpAtv">
									<view class="atvList" v-if="item.persion_num">
										<view class="atv" v-for="(itemDetail, index) in item.persion_image" :key="index" v-if="index < 3">
											<image v-if="itemDetail" mode="aspectFill" :src="itemDetail" />
											<image v-else mode="aspectFill" src="../static/sns/ry_avatar.png" />
										</view>
										<view class="joinNum">等{{ item.persion_num }}人参加</view>
									</view>
									<view v-else-if="item.limit_persion_num">
										<view class="joinNum onlyNum">{{item.limit_persion_num}}个名额，等你来参加</view>
									</view>
								</view>
							</view>
							<!-- 活动参加状况展示 -->
							<view class="signUpInfo">
								<!-- 
								<view class="btnBox" :class="item.type_status === '进行中' && item.sigin_status !== '报名人数已满' ? '' : 'gray' ">
									<view class="join" v-if="item.type_status === '进行中' && item.sigin_status === '报名人数已满' ">名额已满</view>
									<view class="join" v-else>{{item.type_status}}</view>
								</view>
								 -->
								 <view class="btnBox" :class="item.type_status === '未开始' || item.type_status === '已结束' ? 'gray' : ''">
								 	<view class="join">{{item.type_status}}</view>
								 </view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="no-content">暂无相关数据... 😢</view>
			<login></login>
		</scroll-view>
	</view>
</template>

<script>
	import {
		$storage
	} from '@/utils'
	export default {
		data() {
			return {
				activity_catagory: '晒图征文',
				activityFreshing: false,
				activityTriggered: false,
				https: 'https://',
				emit: false,
				activityQuery: {
					userId: '',
					attend: false,
					activity_catagory: '晒图征文',
					is_syn:2,
					page: 1,
				},
				listData: {
					data: []
				},
			}
		},
		components: {
			// login
		},
		onLoad(){
			wx.showShareMenu({
			  withShareTicket: true,
			  menus: ['shareAppMessage', 'shareTimeline']
			})
		},
		created: function() {
			console.log('created');
			this.fetchActivities()
			let _this = this;
			setTimeout(function() {

				_this.fetchActivities()
			}, 1000)
		},
		methods: {
			// 回到首页
			gotoHome(){
				uni.switchTab({
					url: "/pages/index"
				})
			},
			// 切换栏目
			changeTab(type) {
				if(type == this.activity_catagory) return
				this.activity_catagory = type;
				this.activityQuery.activity_catagory = type;
				this.fetchActivities('refresh');
			},

			// scroll-view到底部加载更多
			async activityScrollToLower() {
				// this.fetchNews('loadMore')
				this.fetchActivities('loadMore')
			},
			async activityScrollRefresh() {
				if (this.activityFreshing) return
				this.activityFreshing = true;
				this.activityTriggered = true;
				await this.fetchActivities('refresh')
				this.activityTriggered = false;
				this.activityFreshing = false;
			},
			onRestore() {
				console.log("onRestore");
			},
			onAbort() {
				console.log("onAbort");
			},
			getDate(d) {
				return d ? new Date(d) : new Date()
			},
			activityStartTime(StartTime) {
				console.log(StartTime)
				const start = this.formatTimestamp(StartTime)
				var timestamp = Date.parse(this.getDate())
				var date = this.getDate(timestamp)
				//获取年份
				var Y = date.getFullYear()
				var YY = StartTime.substring(0, 4)
				console.log(start)
				// console.log(Y, YY)
				if (Y != YY) {
					return start
				} else {
					return start.slice(5)
				}
			},
			/** 将时间戳转换 */
			formatTimestamp(d, format = 'YYYY-MM-DD hh:mm') {
				const date = this.getDate(d)
				let hour = date.getHours()
				let minute = date.getMinutes()
				let second = date.getSeconds()
				const year = date.getFullYear()
				let month = date.getMonth()
				let day = date.getDate()
				if (hour < 10) {
					hour = '0' + hour
				}
				if (minute < 10) {
					minute = '0' + minute
				}
				if (second < 10) {
					second = '0' + second
				}
				month = month + 1
				if (month < 10) {
					month = 0 + month
				}
				if (day < 10) {
					day = 0 + day
				}
				const time = `${year}年${month}月${day}日开始`
					// format === 'YYYY-MM-DD hh:mm' ?
					// `${year}年${month}月${day}日 ${hour}:${minute} 开始` :
					// format === 'YYYYMMDDhhmmss' ?
					// `${year}年${month}月${day}日 ${hour}:${minute}:${second} 开始` :
					// `${year}年${month}月${day}日 ${hour}:${minute}:${second} 开始`

				return time
			},
			/* 获取活动列表 */
			async fetchActivities(type = '') {
				const {
					data: {
						activityQuery,
						listData
					},
				} = {
					data: {
						activityQuery: this.activityQuery,
						listData: this.listData
					}
				}
				const {
					data = [],
						canLoaded = true,
						loaded = false
				} = listData
				// debugger
				console.log(loaded)
				if (['refresh', ''].includes(type)) {
					if (type === '' && loaded) {
						return
					}
					wx.showLoading({
						title: '加载中',
					})
					this.loading = true;

					await this.$u.api
						.getActivityList(activityQuery)
						.then((res) => {
							const result = res
							let data = result.data.data.map(item => {
								item.start_time && (item.start_time = this.activityStartTime(item.start_time))
							})
							this.listData = {
								data: result.data.data,
								canLoaded: result.current_page < result.last_Page,
								loaded: true,
								page: result.current_page,
							}
							console.log(this.listData)

							this.loading = false
						})
						.catch((error) => {
							console.log(error)
							// return wx.navigateTo({
							// 	url: `/pages/not-page/not-page?type=${error.statusCode}`,
							// })
						})
					wx.hideLoading()
				}
				if (canLoaded) {
					if (type === 'loadMore') {
						activityQuery.page += 1
						wx.showLoading({
							title: '加载中',
						})
						// this.setData({
						// 	loading: true,
						// })
						const result = await this.$u.api.getActivityList(activityQuery)
						let data = result.data.data.map(item => {
							item.start_time && (item.start_time = this.activityStartTime(item.start_time))
						})
						this.listData = {
							data: data,
							canLoaded: result.current_page < result.last_Page,
							loaded: true,
							page: result.current_page,
						}
						this.activityQuery = activityQuery
						// this.setData({
						// 	loading: false,
						// })
						wx.hideLoading()
					}
				}
			},
			/** 活动详情 */
			todetail(e) {
				const {
					currentTarget: {
						dataset: {
							id
						},
					},
				} = e
				console.log(id)
				// debugger
				const type_status = e.currentTarget.dataset.type_status
				/*
				if(type_status == "未开始"){
					uni.showToast({
						title: '活动尚未开始',
						icon: 'none',
						duration: 1000,
					})
					return
				}  else if(type_status == "已结束") {
					uni.showToast({
						title: '活动尚已结束',
						icon: 'none',
						duration: 1000,
					})
					return
				} */
				uni.navigateTo({
					url: "/activities/detail?id=" + id
				});
			},
			async goJoin(e) {
				console.log('这是纯问卷', e)
				const activeId = e.currentTarget.dataset.id
				const type_status = e.currentTarget.dataset.type_status
				if(type_status == "未开始"){
					uni.showToast({
						title: '活动尚未开始',
						icon: 'none',
						duration: 1000,
					})
					return
				} else if(type_status == "已结束") {
					uni.showToast({
						title: '活动尚已结束',
						icon: 'none',
						duration: 1000,
					})
					return
				}
				const userTest = $storage.get('user')
				console.log('userTest++++++++++', userTest)

				if (userTest !== undefined) {
					// let url = 'https://mms-api.royole.fun/api/v1/template_type/1290926889229225984?userid=1283587362111074304'
					new Promise((resolve, reject) => {
							wx.request({
								url: 'https://mms-api.royole.fun/api/v1/template_type/' + activeId + '?userid=' + userTest.rouyu_uid,
								data: {},
								method: 'GET',
								header: {
									'X-Auth-Token': `${$storage.get('passportToken')}`,
									'Paasport-Device-Id': $storage.get('rouyu-device-id'),
									'Paasport-App-Id': $storage.get('rouyu-app-id'),
									'X-Auth-UID': $storage.get('rouyu-user-id'),
								},
								success: (res) => {
									return resolve(res.data)
									// }
								},
								fail: (e) => {
									console.log(e)
									return reject(e)
								},
							})
						})
						.then((res) => {
							console.log('res+++', res)
							if (!res.data.user_attend) {
								// 数据埋点
								this.$$Rangers.event('enroll', {
									activity_name: '纯表单参与',
								    platform: '小程序',
								})
								uni.navigateTo({
									url: '/activities/joinActivity?activityId=' + activeId,
								})
							} else {
								uni.showToast({
									title: '您已填过啦',
									icon: 'none',
									duration: 1000,
								})
							}
						})
				} else {
					uni.$emit('login')
				}
				// await this.$u.api.getUserActivityDetail(activeId, userTest.rouyu_uid, {})
			},

		},
	}
</script>

<style lang="scss">
	@import '../var.scss';
	@import '../common.scss';

	.activityPage {
		background: linear-gradient(#001432, #F9F9F9);
		height: 100%;
	}
	.hicon{
		height: 32upx;
		width: 32upx;
		padding-left: 30upx;
		padding-top: 10upx;
	}
	.no-content {
		display: flex;
		justify-content: center;
		padding-top: 200upx;
		color: #fff;
	}
	.activityTabItem {
		padding: 22upx 40upx 32upx 40upx;
		display: flex;
		justify-content: center;
		align-items: center;
		.tabItem {
			&.orange {
				background: url(../static/sns/activity_essay@2x.png) no-repeat;
				background-size: cover;
				margin-right: 10upx;
			}
			&.green {
				background: url(../static/sns/activity_chart@2x.png) no-repeat;
				background-size: cover;
				margin-right: 10upx;
			}
			&.blue {
				background: url(../static/sns/activity_outside@2x.png) no-repeat;
				background-size: cover;
			}
			color: #fff;
			width: 220upx;
			height: 90upx;
			border-radius: 8upx;
			font-size: 32upx;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			.activeItem {
				width: 28upx;
				height: 6upx;
				border-radius: 2upx;
				background-color: #fff;
				margin-top: 10upx;
				visibility: hidden;
			}
			&.active {
				.activeItem {
					visibility: inherit;
				}
			}
		}
	}
	.scrollView {
		height: calc(100vh - 268upx);
	}
	.section {
		width: 100%;
		.list {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 674upx;
			min-height: 406upx;
			margin: 0upx 40upx 44upx 39upx;
			border-bottom: 1upx solid $border-color;
			background-color: #fff;
			border-radius: 16upx;
			.imgContainer {
				width: 674upx;
				height: 274upx;
				border-top-left-radius: 16upx;
				border-top-right-radius: 16upx;
				background-color: #999999;
				overflow: hidden;

				.img {
					width: 100%;
					height: 100%;
					border-top-left-radius: 16upx;
					border-top-right-radius: 16upx;
				}
			}

			.content {
				width: 100%;
				padding-left: 36upx;
				padding-top: 10upx;
				color: $title-color;
				display: flex;
				min-height: 132upx;
				align-items: center;

				.content-left {
					width: 458upx;
					height: 100%;
					.signUpAtv {
						display: flex;
						flex-direction: row;
						align-items: center;
						padding-right: 40upx;
						margin-top: 10upx;
						.onlyNum {
							margin-bottom: 34upx;
						}

						.atvList {
							display: flex;
							flex-direction: row;
							align-items: center;
							margin-bottom: 20upx;

							.atv {
								width: 40upx;
								height: 40upx;
								margin: 0 5upx;
								border-radius: 20upx;
								overflow: hidden;

								image {
									width: 100%;
									height: 100%;
								}
							}

							.joinNum {
								color: #757474;
								font-size: 24upx;
								margin-left: 16upx;
							}


						}
					}
				}

				.activeContent {
					width: 100%;
					margin-bottom: 12upx;
					line-height: 36upx;
					font-size: 24upx;
					color: #757474;
				}

				.activeDetail {
					display: flex;
					flex-direction: row;
					flex-wrap: wrap;
					margin-bottom: 12upx;
					align-items: center;
					color: #757474;
					font-size: 24upx;

					text {
						margin: 0 10upx;
					}
				}

				.type {
					width: 100%;
					font-size: 22upx;
					line-height: 22upx;
				}

				.title {
					width: 100%;
					margin-top: 10upx;
					margin-bottom: 10upx;
					font-weight: 600;
					font-size: 32upx;
					line-height: 40upx;
					color: #001432;
				}

				.detail {
					width: 100%;
					margin-top: 0;
					margin-bottom: 12upx;
					color: $info-color;
					font-weight: 600;
					font-size: 24upx;
				}
			}

			.signUpInfo {
				// padding: 20upx 0;
				margin: 20upx 0;
				height: 100%;


				.btnBox {
					width: 146upx;
					height: 54upx;
					background-color: #0046f5;
					border-radius: 33upx;
					display: flex;
					align-items: center;

					&.gray {
						background-color: #afb4be;
					}

					// line-height: 48upx;
					.join {
						width: 100%;
						height: 22upx;
						color: #ffffff;
						font-size: 22upx;
						line-height: 22upx;
						text-align: center;
					}
				}

				.jioned {
					background-color: #afb4be;
				}
			}
		}
	}
</style>
